package pl.diagnoser.client;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import pl.diagnoser.client.dto.ObjectHistoryViewer;
import pl.diagnoser.client.dto.ObjectsDTO;
import pl.diagnoser.client.dto.SearchResultDTO;
import pl.diagnoser.client.tools.DataGetterService;
import pl.diagnoser.client.tools.DataGetterServiceAsync;
import pl.diagnoser.client.tools.DiagnoserProperties;
import pl.diagnoser.client.tools.LogIn;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.types.ListGridFieldType;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.Button;
import com.smartgwt.client.widgets.Canvas;
import com.smartgwt.client.widgets.Label;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.CloseClickEvent;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.form.fields.events.ChangedEvent;
import com.smartgwt.client.widgets.form.fields.events.ChangedHandler;
import com.smartgwt.client.widgets.grid.CellFormatter;
import com.smartgwt.client.widgets.grid.ListGrid;
import com.smartgwt.client.widgets.grid.ListGridField;
import com.smartgwt.client.widgets.grid.ListGridRecord;
import com.smartgwt.client.widgets.layout.HLayout;
import com.smartgwt.client.widgets.layout.VLayout;

public class ObjectHandling extends Canvas {
	
	private ObjectDetailsForm objectDetailsForm;
	private final DiagnoserProperties properties = new DiagnoserProperties();
	private final SelectItem historySelector = new SelectItem();
	private DataGetterServiceAsync dataGetterAsc = GWT.create(DataGetterService.class);
	private ListGrid listGrid = new ListGrid();
	
	public ObjectHandling() {
		super();
		
		final HLayout mainLayout = new HLayout();
		mainLayout.setWidth100();
		mainLayout.setHeight100();
		mainLayout.setMargin(5);
		mainLayout.setMembersMargin(10);
		
		objectDetailsForm = new ObjectDetailsForm(new ObjectsDTO("",Long.parseLong("0")), true, false, true);
		objectDetailsForm.setWidth(430);
		objectDetailsForm.setObjectHandling(this);
		mainLayout.addMember(objectDetailsForm);
		
		final Button addNewObjectBt = new Button();
		addNewObjectBt.setHeight(18);
		addNewObjectBt.setTitle("addNewObjectBt");
		properties.getWidgetTitle("addNewObjectBt", addNewObjectBt);
		addNewObjectBt.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				final Window addNewObjectWindow = new Window();
				addNewObjectWindow.setWidth(370);
				addNewObjectWindow.setHeight(250);
		        addNewObjectWindow.setShowMinimizeButton(false);
		        addNewObjectWindow.setIsModal(true);
		        addNewObjectWindow.setShowModalMask(true);
		        addNewObjectWindow.centerInPage();
		        addNewObjectWindow.setTitle("addNewObjectWindow");
		        properties.getWidgetTitle("addNewObjectWindow", addNewObjectWindow);
		        addNewObjectWindow.addCloseClickHandler(new CloseClickHandler() {
			           public void onCloseClick(CloseClickEvent event) {
			        	   addNewObjectWindow.destroy();
						}
			        });
		        final AddNewObjectLayout newObjectLayout = new AddNewObjectLayout(addNewObjectWindow, returnMe(), objectDetailsForm.getObjectSelection());
		        addNewObjectWindow.addItem(newObjectLayout.getNewObject());
		        addNewObjectWindow.show();
			}
		});
		
		if(LogIn.getInstance().getUser().getAppId() == LogIn.SEARCH_APP) {
			mainLayout.addMember(addNewObjectBt);
			final VLayout historyLayout = new VLayout();
			historyLayout.setShowEdges(true);
			historyLayout.setWidth100();
			historyLayout.setHeight100();
			historyLayout.setMembersMargin(5);
			
			final HLayout historyChoiserLayout = new HLayout();
			historyChoiserLayout.setWidth100();
			historyChoiserLayout.setHeight(20);
			historyChoiserLayout.setMembersMargin(10);
			
			final ObjectDetailsForm historyDetails = new ObjectDetailsForm(new ObjectsDTO("",Long.parseLong("0")), false, false, false);
			historyDetails.setWidth(275);
			historyDetails.setWidth(430);
			historyDetails.setAlign(Alignment.CENTER);
			
			final Label historyLabel = new Label();
			historyLabel.setHeight(18);
			historyLabel.setWidth(150);
			historyLabel.setAlign(Alignment.CENTER);
			historyLabel.setContents("historyLabel");
			properties.getLabelTitle("historyLabel", historyLabel);
			historyChoiserLayout.addMember(historyLabel);
			
			final DynamicForm form = new DynamicForm();
			historySelector.setShowTitle(false);
			historySelector.setHeight(18);
			historySelector.setAlign(Alignment.CENTER);
			historySelector.addChangedHandler(new ChangedHandler() {
				public void onChanged(ChangedEvent event) {
					historyDetails.getHistoryObjectAttributes(Long.valueOf((String)event.getItem().getValue()).longValue());
				}
			});
			form.setFields(historySelector);
			form.setAlign(Alignment.CENTER);
			form.setHeight(18);
			historyChoiserLayout.addMember(form);
			
			historyLayout.addMember(historyChoiserLayout);
			historyLayout.addMember(historyDetails);
			mainLayout.addMember(historyLayout);
		}
		else if(LogIn.getInstance().getUser().getAppId() != LogIn.SEARCH_APP) {
			VLayout buttonLayout = new VLayout();
			buttonLayout.setWidth(50);
			buttonLayout.addMember(addNewObjectBt);
			
			final Button addNewEstimate = new Button();
			addNewEstimate.setHeight(18);
			addNewEstimate.setTitle("addNewEstimate");
			properties.getWidgetTitle("addNewEstimate", addNewEstimate);
			addNewEstimate.addClickHandler(new ClickHandler() {
                public void onClick(ClickEvent event) {
                	if(objectDetailsForm.getSelectedObject() == null ) {
                    	SC.say("Najpierw proszę wybrać obiekt");
                    	return;
                	}
                	
                	final Window newObjectEstimateWindow = new Window();
                    final AddNewObjectEstimateLayout newEstimate = 
                                    new AddNewObjectEstimateLayout( newObjectEstimateWindow, returnMe(), objectDetailsForm.getSelectedObject() );
                    
                    newObjectEstimateWindow.setWidth(765);
                    newObjectEstimateWindow.setHeight(450);
                    
                    newObjectEstimateWindow.setTitle("Dodaj nowe badanie");
                    properties.getWidgetTitle("newObjectEstimateWindow", newObjectEstimateWindow);
                    
                    newObjectEstimateWindow.setShowMinimizeButton(false);
                    newObjectEstimateWindow.setIsModal(true);
                    newObjectEstimateWindow.setShowModalMask(true);
                    newObjectEstimateWindow.centerInPage();
                    newObjectEstimateWindow.addItem(newEstimate.initLayout());
                    newObjectEstimateWindow.addCloseClickHandler(new CloseClickHandler() {
                    	public void onCloseClick(CloseClickEvent event) {
                    		newObjectEstimateWindow.destroy();
                    	}
                    });
                    newObjectEstimateWindow.show();
                }
			});
			buttonLayout.addMember(addNewEstimate);
			mainLayout.addMember(buttonLayout);
			
			listGrid.setHeight100();
			listGrid.setWidth(480);
			ListGridField rowNum = new ListGridField("estimateNum", "LP");
	        rowNum.setType(ListGridFieldType.INTEGER);
	        rowNum.setWidth(50);
	        rowNum.setCellFormatter(new CellFormatter() {  
	            public String format(Object value, ListGridRecord record, int rowNum, int colNum) {  
	                return rowNum + 1 + "";  
	            }  
	        });
	        
	        ListGridField estimateDate = new ListGridField("estimateDate","listGrid.estimateDate", 90);
	        estimateDate.setType(ListGridFieldType.DATE);
	        ListGridField estimateSymptoms = new ListGridField("estimateSymptoms", "listGrid.estimateSymptoms", 500);  
	        ListGridField estimateDefect = new ListGridField("estimateDefect", "listGrid.estimateDefect", 190);
	        
	        listGrid.setFields(rowNum, estimateDate, estimateDefect, estimateSymptoms);
	        properties.getListGridTitle("estimateDate", "listGrid", listGrid, true);
	        properties.getListGridTitle("estimateSymptoms", "listGrid", listGrid, true);
	        properties.getListGridTitle("estimateDefect", "listGrid", listGrid, true);

	        mainLayout.addMember(listGrid);
		}
		
		this.addChild(mainLayout);
		this.draw();
	}
	
	public void refreshObjectList(final SelectItem objectSelector, final Long ident) {
		objectDetailsForm.refreshObjectList(objectSelector, ident);
	}
	
	public void refreshObjectHistory(long objectId) {
		if (dataGetterAsc == null) {
			dataGetterAsc = GWT.create(DataGetterService.class);
		}
		
		AsyncCallback<List<SearchResultDTO>> callback = new AsyncCallback<List<SearchResultDTO>>() {
			public void onFailure(Throwable caught) {
				System.out.println(caught.getMessage());
			}

			public void onSuccess(List<SearchResultDTO> result) {
				historySelector.setValueMap(generateHistoryDateToCombo(result));
			}
		};
		
		dataGetterAsc.getSearchResultForObject(objectId, callback);
	}
	
	private LinkedHashMap<String, String> generateHistoryDateToCombo( List<SearchResultDTO> searchResult ) {
		LinkedHashMap<String, String> retVal = new LinkedHashMap<String, String>();
		if(searchResult != null) {
			for(SearchResultDTO result : searchResult) {
				retVal.put("" + result.getSearchResultId(), result.getDate().toString());
			}
		}
		
		return retVal;
	}
	
	private ObjectHandling returnMe() {
		return this;
	}
	
	public void refreshObjectEstimates(Long id) {
        ObjectEstimatesData data = new ObjectEstimatesData( id, listGrid );
        data.getRecords();
	}

}

class ObjectEstimatesRecord extends ListGridRecord {
        
        ObjectEstimatesRecord() {}
        ObjectEstimatesRecord(String estimateDate, String estimateSymptoms, String estimateResult) {
                setEstimateDate(estimateDate);
                setEstimateSymptoms(estimateSymptoms);
                setEstimateResult(estimateResult);
        }
        
        public void setEstimateDate(String estimateDate) {
                setAttribute("estimateDate", estimateDate);
        }
        
        public String getEstimateDate() {
                return getAttributeAsString("estimateDate");
        }
        
        public void setEstimateSymptoms(String estimateSymptoms) {
                setAttribute("estimateSymptoms", estimateSymptoms);
        }
        
        public String getEstimateSymptoms() {
                return getAttributeAsString("estimateSymptoms");
        }
        
        public void setEstimateResult(String estimateDefect) {
                setAttribute("estimateDefect", estimateDefect);
        }
        
        public String getEstimateResult() {
                return getAttributeAsString("estimateDefect");
        }
        
        public String getFieldValue(String field) {
                return getAttributeAsString(field);
        }
}

class ObjectEstimatesData {
        
        private static DataGetterServiceAsync dataGetterAsc = GWT.create(DataGetterService.class);
        private static Long objectId;
        private static ListGrid list;
        
        ObjectEstimatesData(Long id, ListGrid listGrid) {
                objectId = id;
                list= listGrid;
        }
        
        public void getRecords() {
                
                final ArrayList<ObjectEstimatesRecord> records = new ArrayList<ObjectEstimatesRecord>();
                
                if (dataGetterAsc == null) {
                        dataGetterAsc = GWT.create(DataGetterService.class);
                }
                
                AsyncCallback<List<ObjectHistoryViewer>> callback = new AsyncCallback<List<ObjectHistoryViewer>>() {
                        public void onFailure(Throwable caught) {
                                System.out.println(caught.getMessage());
                        }

                        public void onSuccess(List<ObjectHistoryViewer> result) {
                            for(ObjectHistoryViewer viewer : result) {
                            	records.add(new ObjectEstimatesRecord( viewer.getEstimate().getEstDate(),
                            										   viewer.getSymptomsAsString(),
                                                                       viewer.getEstimate().getDefect()
                                                                     ));
                            }
                            list.setData(records.toArray(new ObjectEstimatesRecord[records.size()]));
                        }
                };

                dataGetterAsc.getEstimateForObject(objectId,callback);
        }
}
